package com.dongdong.controller;


import cn.hutool.core.util.StrUtil;
import com.dongdong.model.TbSeller;
import com.dongdong.result.PageBean;
import com.dongdong.result.PageResult;
import com.dongdong.result.Result;
import com.dongdong.result.ResultEnums;
import com.dongdong.service.SellerService;
import com.dongdong.vo.TbSellerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

import static com.dongdong.utils.ShiroUtils.encryptPassword;
import static com.dongdong.utils.ShiroUtils.generateSalt;

@RestController
@RequestMapping("seller")
public class SellerController {
    @Autowired
    private SellerService sellerService;


    @GetMapping("selectSellerByUsername")
    public TbSeller selectSellerByUsername(@RequestParam String name) {

        if (StrUtil.isEmpty(name)) {
            return null;
        }
    return sellerService.selectSellerByUsername(name);
    }




    @GetMapping("/unameseller")  //注册时保障账号唯一性
    public int  unameseller (@RequestParam String uname){
        return sellerService.unameseller(uname);
    }
    //注册
    @PostMapping("/sellerregiestadd")
    public Result sellerregiestadd(@RequestBody TbSellerVO sellerVO) {
        if (StrUtil.isEmpty(sellerVO.getSellerId())) {
            return Result.ERROR().setData("id不可为空"); //
        }
        if (StrUtil.isEmpty(sellerVO.getName())) {
            return Result.ERROR().setData("name不可为空"); //
        }
        if (StrUtil.isEmpty(sellerVO.getPassword())) {
            return Result.ERROR().setData("密码不可为空"); //
        }

        String salt1 = generateSalt(6);
        sellerVO.setSalt(salt1);
        sellerVO.setPassword(encryptPassword("md5", sellerVO.getPassword(), salt1,5));//密5次
        return sellerService.sellerregiest(sellerVO);
    }


//分页
    @PostMapping("/findSellerPage")
    public Result findSellerPage(@RequestBody PageBean<TbSeller> pageBean){
        PageResult result = sellerService.findSellerPage(pageBean);
        return Result.OK().setData(result);
    }

//详情
    @GetMapping("/selectSellerBySellerId")
    public TbSeller selectSellerBySellerId(@RequestParam String sellerId) throws Exception {

        if(Objects.equals(sellerId, "yijia")){
            try {
                Thread.sleep(  100);       //睡眠100毫秒
            } catch (InterruptedException e) {
               e.printStackTrace();
            }

        }
        else if(Objects.equals(sellerId, "baidu")){
            throw new Exception("测试手动创建异常");
        }
        return sellerService.selectSellerBySellerId(sellerId);
    }

//审核
    @PostMapping("/updateSeller")
    public Result updateSeller(@RequestParam String status,@RequestParam String sellerId){
        sellerService.updateSeller(status,sellerId);
        return Result.OK();
    }






}
